package com.banmoon.queue;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class ArrayBlockingQueueTest {

    public static void main(String[] args) throws InterruptedException {
        putTest();
        System.out.println("========= 分割线 =========");
        takeTest();
    }

    public static void putTest() throws InterruptedException {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

        new Thread(() -> {
            try {
                // 3秒后再取出
                TimeUnit.SECONDS.sleep(3);
                String ele = queue.take();
                System.out.println(ele + "已取出：" + DateUtil.formatTime(new Date()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        queue.put("1");
        System.out.println(StrUtil.format("{}已插入，{}", 1, DateUtil.formatTime(new Date())));
        queue.put("2");
        System.out.println(StrUtil.format("{}已插入，{}", 2, DateUtil.formatTime(new Date())));
        queue.put("3");
        System.out.println(StrUtil.format("{}已插入，{}", 3, DateUtil.formatTime(new Date())));
        queue.put("4");
        System.out.println(StrUtil.format("{}已插入，{}", 4, DateUtil.formatTime(new Date())));
    }

    private static void takeTest() throws InterruptedException {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

        // 其他线程插入数据
        for (int i = 1; i <= 3; i++) {
            String str = StrUtil.toString(i);
            new Thread(() -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                    queue.put(str);
                    System.out.println(StrUtil.format("{}已插入，{}", str, DateUtil.formatTime(new Date())));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

        // 直接取数
        System.out.println(queue.take() + "已取出：" + DateUtil.formatTime(new Date()));
        System.out.println(queue.take() + "已取出：" + DateUtil.formatTime(new Date()));
        System.out.println(queue.take() + "已取出：" + DateUtil.formatTime(new Date()));


    }

}
